/*  
 * cafe-datepicker.js
 * @Author :      GUORUI
 * @CreateDate :  2017年6月14日
 * Copyright (c) 2017, NRIET.　
 * 日期控件
 */

;define(function(){
	/**
	 * 创建控件界面
	 */
	function getNodeHtml(cfg){
		var wrapper = $('<div>').addClass("datepicker");
		if(1 == cfg.type){
			style1(wrapper,cfg);
		}else if(2 == cfg.type){
			style2(wrapper,cfg);
		}else if(3 == cfg.type){
			style3(wrapper,cfg);
		}else if(4 == cfg.type){
			style4(wrapper,cfg);
		}else if(5 == cfg.type){
			style5(wrapper,cfg);
		}else if(6 == cfg.type){
			style6(wrapper,cfg);
		}else if(7 == cfg.type){
			style7(wrapper,cfg);
		}else if(8 == cfg.type){
			style8(wrapper,cfg);
		}else if(9 == cfg.type) {
            style9(wrapper, cfg);
        }else if(10 == cfg.type){
        	style10(wrapper,cfg);
    	}else{
			defStyle(wrapper,cfg);
		}
		return wrapper;
	}
	function defStyle($wrapper,cfg){
		var $date = $('<div>').addClass("datepicker-date"),
		$dateCtl = $('<div>').addClass("datepicker-dateCtl"),
		$left = $('<div>').addClass("datepicker-left"),
		$right = $('<div>').addClass("datepicker-right"),
		$query = $('<div>').addClass("datepicker-query"),
		$refresh = $('<div>').addClass("datepicker-refresh");
		$date.append($('<span>').text(getShowDate(cfg)));
		$left.append($('<i>').addClass("datepicker-left-cion")).append($('<span>').text(cfg.timeInterval));
		$right.append($('<span>').text(cfg.timeInterval)).append($('<i>').addClass("datepicker-right-cion"));
		$query.append($('<i>'));
		$refresh.append($('<i>'));
		$dateCtl.append($left).append($right).append($query).append($refresh);
		
		var $realTimePush = $('<div>').addClass("datepicker-realTimePush");
		$realTimePush.append($('<span>').text("实时推送")).append($('<i>').addClass("datepicker-realTimePush-btn"));
		
		$wrapper.append($date).append($dateCtl).append($realTimePush);
	}
	//只有日期选择
	function style1($wrapper,cfg){
		var $date = $('<div>').addClass("datepicker-date style-1");
		$date.append($('<span>').text(getShowDate(cfg)));
		$wrapper.append($date);
	}
	//有日期选择、查询按钮和刷新按钮、实时推送
	function style2($wrapper,cfg){
		var $date = $('<div>').addClass("datepicker-date"),
		$dateCtl = $('<div>').addClass("datepicker-dateCtl style-9"),
		$query = $('<div>').addClass("datepicker-query"),
		$refresh = $('<div>').addClass("datepicker-refresh");
		$date.append($('<span>').text(getShowDate(cfg)));
		$query.append($('<i>'));
		$refresh.append($('<i>'));
		$dateCtl.append($query).append($refresh);
		
		var $realTimePush = $('<div>').addClass("datepicker-realTimePush");
		$realTimePush.append($('<span>').text("实时刷新")).append($('<i>').addClass("datepicker-realTimePush-btn"));
		
		$wrapper.append($date).append($dateCtl).append($realTimePush);
	}
	//有日期选择、左右按钮和刷新按钮
	function style3($wrapper,cfg){
		var $date = $('<div>').addClass("datepicker-date"),
		$dateCtl = $('<div>').addClass("datepicker-dateCtl"),
		$left = $('<div>').addClass("datepicker-left"),
		$right = $('<div>').addClass("datepicker-right"),
		$query = $('<div>').addClass("datepicker-query"),
		$refresh = $('<div>').addClass("datepicker-refresh");
		$date.append($('<span>').text(getShowDate(cfg)));
		$left.append($('<i>').addClass("datepicker-left-cion")).append($('<span>').text(cfg.timeInterval));
		$right.append($('<span>').text(cfg.timeInterval)).append($('<i>').addClass("datepicker-right-cion"));
		$query.append($('<i>'));
		$refresh.append($('<i>'));
		$dateCtl.append($left).append($right).append($query).append($refresh);
		
		$wrapper.append($date).append($dateCtl);
	}
	//只有日期选择
	function style4($wrapper,cfg){
		var $date = $('<div>').addClass("datepicker-date style-4");
		$date.append($('<span>').text(getShowDate(cfg)));
		
		$wrapper.append($date);
	}
	//有日期选择、小时选择、左右按钮和刷新按钮
	function style5($wrapper,cfg){
		var showDate = new Date(cfg.curDate);
		var $date = $('<div>').addClass("datepicker-date style-5"),
		$hour = $('<div>').addClass("datepicker-hour"),
		$dateCtl = $('<div>').addClass("datepicker-dateCtl style-5"),
		$left = $('<div title="向前">').addClass("datepicker-left"),
		$right = $('<div title="向后">').addClass("datepicker-right"),
		$refresh = $('<div title="最新">').addClass("datepicker-refresh style-2");
		$date.append($('<span>').text(showDate.format("yyyy-MM-dd")));
		$hour.append($('<span>').text(showDate.format("hh"))).append($('<span>').text("时"));
		$left.append($('<i>').addClass("style-3"));
		$right.append($('<i>').addClass("style-3"));
		$refresh.append($('<i>').addClass("style-5"));
		$dateCtl.append($left).append($right).append($refresh);
		
		$wrapper.append($date).append($hour).append($dateCtl);
	}
	//有日期选择、左右按钮、查询按钮、刷新按钮、时效间隔选择和实时推送按钮
	function style6($wrapper,cfg){
		var $date = $('<div>').addClass("datepicker-date"),
		$dateCtl = $('<div>').addClass("datepicker-dateCtl style-6"),
		$left = $('<div>').addClass("datepicker-left"),
		$right = $('<div>').addClass("datepicker-right"),
		$query = $('<div>').addClass("datepicker-query"),
		$refresh = $('<div>').addClass("datepicker-refresh"),
		$timeInterval = $('<div>').addClass("datepicker-timeInterval");
		$date.append($('<span>').text(getShowDate(cfg)));
		$left.append($('<i>').addClass("datepicker-left-cion")).append($('<span>').text(cfg.timeInterval));
		$right.append($('<span>').text(cfg.timeInterval)).append($('<i>').addClass("datepicker-right-cion"));
		$query.append($('<i>'));
		$refresh.append($('<i>'));
		$dateCtl.append($left).append($right).append($query).append($refresh);
		$timeInterval.append($('<span>').text("5分钟")).append($('<span>').append($('<i>').addClass("cafe-ifont cafe-ic-xiala1")));
		
		var $realTimePush = $('<div>').addClass("datepicker-realTimePush");
		$realTimePush.append($('<span>').text("实时推送")).append($('<i>').addClass("datepicker-realTimePush-btn"));
		
		$wrapper.append($date).append($dateCtl).append($timeInterval).append($realTimePush);
	}
	//有日期选择、左右按钮、查询按钮和刷新按钮
	function style7($wrapper,cfg){
		var $date = $('<div>').addClass("datepicker-date style-7"),
		$dateCtl = $('<div>').addClass("datepicker-dateCtl"),
		$left = $('<div>').addClass("datepicker-left"),
		$right = $('<div>').addClass("datepicker-right"),
		$query = $('<div>').addClass("datepicker-query"),
		$refresh = $('<div>').addClass("datepicker-refresh");
		$date.append($('<span>').text(getShowDate(cfg)));
		$left.append($('<i>').addClass("datepicker-left-cion")).append($('<span>').text(cfg.timeInterval));
		$right.append($('<span>').text(cfg.timeInterval)).append($('<i>').addClass("datepicker-right-cion"));
		$query.append($('<i>'));
		$refresh.append($('<i>'));
		$dateCtl.append($left).append($right).append($query).append($refresh);
		
		$wrapper.append($date).append($dateCtl);
	}
	//有日期选择、小时选择、分钟选择、左右按钮、查询按钮和刷新按钮
	function style8($wrapper,cfg){
		var $date = $('<div>').addClass("datepicker-date style-1 style-8"),
		$hourSel = $('<div>').addClass("datepicker-hoursel"),
		$minSel = $('<div>').addClass("datepicker-minsel"),
		$dateCtl = $('<div>').addClass("datepicker-dateCtl style-8"),
		$lleft = $('<div>').addClass("datepicker-lleft"),
		$left = $('<div>').addClass("datepicker-left"),
		$right = $('<div>').addClass("datepicker-right"),
		$rright = $('<div>').addClass("datepicker-rright"),
		$query = $('<div>').addClass("datepicker-query"),
		$refresh = $('<div>').addClass("datepicker-refresh");
		
		var showDate = new Date(cfg.curDate);
		$date.append($('<span>').text(showDate.format("yyyy-MM-dd")));
		$hourSel.append($('<span>').text(showDate.format("hh"))).append($('<span>').text("时"));
		$minSel.append($('<span>').text(showDate.format("mm"))).append($('<span>').text("分"));
		$lleft.append($('<i>').addClass("datepicker-lleft-cion")).append($('<span>').text(cfg.ttimeInterval));
		$left.append($('<i>').addClass("datepicker-left-cion")).append($('<span>').text(cfg.timeInterval));
		$right.append($('<span>').text(cfg.timeInterval)).append($('<i>').addClass("datepicker-right-cion"));
		$rright.append($('<span>').text(cfg.ttimeInterval)).append($('<i>').addClass("datepicker-rright-cion"));
		$query.append($('<i>'));
		$refresh.append($('<i>'));
		$dateCtl.append($lleft).append($left).append($right).append($rright).append($refresh).append($query);
		
		$wrapper.append($date).append($hourSel);
		if("M" == cfg.dateType){
			$wrapper.append($minSel);
		}
		$wrapper.append($dateCtl);
	}
    //有日期选择、左右按钮
    function style9($wrapper,cfg){
        var $date = $('<div>').addClass("datepicker-date style-1"),
            $dateCtl = $('<div>').addClass("datepicker-dateCtl style-2"),
            $left = $('<div>').addClass("datepicker-left"),
            $right = $('<div>').addClass("datepicker-right"),
        	$refresh = $('<div>').addClass("datepicker-refresh"),
        	$query = $('<div>').addClass("datepicker-query");
        $date.append($('<span>').text(getShowDate(cfg)));
        $left.append($('<i>').addClass("style-3"));
        $right.append($('<i>').addClass("style-3"));
        $refresh.append($('<i>').addClass("style-3"));
        $query.append($('<i>').addClass("style-3"));
        
        $dateCtl.append($left).append($right).append($refresh).append($query);

        $wrapper.append($date).append($dateCtl);
    }
    //有日期选择、小时选择、分钟选择、时间间隔选择、左右按钮、刷新按钮和查询按钮
    function style10($wrapper,cfg){
        var $date = $('<div>').addClass("datepicker-date style-1 style-8"),
            $hourSel = $('<div>').addClass("datepicker-hoursel"),
            $minSel = $('<div>').addClass("datepicker-minsel"),
            $dateCtl = $('<div>').addClass("datepicker-dateCtl style-8"),
            $timeInterval = $('<div>').addClass("datepicker-timeInterval style-10"),
            $left = $('<div>').addClass("datepicker-left"),
            $right = $('<div>').addClass("datepicker-right"),
            $query = $('<div>').addClass("datepicker-query"),
            $refresh = $('<div>').addClass("datepicker-refresh");

        var showDate = new Date(cfg.curDate);
        $date.append($('<span>').text(showDate.format("yyyy-MM-dd")));
        $hourSel.append($('<span>').text(showDate.format("hh"))).append($('<span>').text("时"));
        $minSel.append($('<span>').text(showDate.format("mm"))).append($('<span>').text("分"));
        $timeInterval.append($('<span>').text(cfg.timeIntervals[0].text)).append($('<span>').append($('<i>').addClass("cafe-ifont cafe-ic-xiala1")));
        $left.append($('<i>').addClass("datepicker-left-cion")).append($('<span>').text(cfg.timeInterval));
        $right.append($('<span>').text(cfg.timeInterval)).append($('<i>').addClass("datepicker-right-cion"));
        $query.append($('<i>'));
        $refresh.append($('<i>'));
        $dateCtl.append($timeInterval).append($left).append($right).append($refresh).append($query);

        $wrapper.append($date).append($hourSel);
        if("M" == cfg.dateType){
            $wrapper.append($minSel);
        }
        $wrapper.append($dateCtl);
    }
	/**
	 * 绑定事件
	 */
	function _eves($drop,cfg){
		var $date = $drop.find(".datepicker-date");
		$drop.undelegate().delegate(".datepicker-date","click",function(){//点击日期弹出日期选择窗口
			if(!$drop.find(".datepicker-realTimePush-btn").hasClass("active")){
				var $dpw = $(this).find(".date-pick-wrap");
				if($dpw.length > 0){
                    $dpw.remove();
				}else{
                    if($drop.find(".datepicker-hour-select-wrap").is(":visible")){
                        $drop.find(".datepicker-hour-select-wrap").prev().removeClass("active").end().remove();
                    }
                    if($drop.find(".dp-timeInterval-wrap").is(":visible")){
                        $drop.find(".dp-timeInterval-wrap").remove();
                    }
                    if($drop.find(".datepicker-hmsel").is(":visible")){
                        $drop.find(".datepicker-hmsel").remove();
                    }
                    buildDateLayer($date,cfg);
				}
			}
		}).delegate(".datepicker-hoursel","click",function(){//小时选择窗口
			$(this).find(".datepicker-hmsel").remove();
			var $hmsel = $('<div>').addClass("datepicker-hmsel");
			buildHourOptions($drop,$hmsel,cfg);
			$(this).append($hmsel);
		}).delegate(".datepicker-minsel","click",function(){//分钟选择窗口
			$(this).find(".datepicker-hmsel").remove();
			var $hmsel = $('<div>').addClass("datepicker-hmsel");
			buildMinuteOptions($drop,$hmsel,cfg);
			$(this).append($hmsel);
		}).delegate(".datepicker-lleft","click",function(){//向前切一个范围时次
			cfg.curDate = getDate(new Date(cfg.curDate),-parseInt($(this).text()) * ("M" == cfg.dateType ? 60 : 1),cfg);
			$date.find("span").text(getShowDate(cfg));
			$date.siblings(".datepicker-hoursel").find("span:first").text(new Date(cfg.curDate).format("hh"));
			if("M" == cfg.dateType){
				$date.siblings(".datepicker-minsel").find("span:first").text(new Date(cfg.curDate).format("mm"));
			}
			if($date.find(".date-pick-wrap").is(":visible")){
				buildDateLayer($date,cfg);
			}
			if($.isFunction(cfg.call)){
				cfg.call(cfg.curDate);
			}
		}).delegate(".datepicker-left","click",function(){//向前切一个固定时次
			if(!$drop.find(".datepicker-realTimePush-btn").hasClass("active")){
				cfg.curDate = getDate(new Date(cfg.curDate),-cfg.timeInterval,cfg);
				$date.find("span").text(getShowDate(cfg));
				if(5 == cfg.type){
					$date.next(".datepicker-hour").find("span:first").text(new Date(cfg.curDate).format("hh"));
				}else if(-1 != $.inArray(cfg.type,[8,10])){
					$date.siblings(".datepicker-hoursel").find("span:first").text(new Date(cfg.curDate).format("hh"));
					if("M" == cfg.dateType){
						$date.siblings(".datepicker-minsel").find("span:first").text(new Date(cfg.curDate).format("mm"));
					}
				}
				if($date.find(".date-pick-wrap").is(":visible")){
					buildDateLayer($date,cfg);
				}
				if($.isFunction(cfg.call)){
					cfg.call(cfg.curDate);
				}
			}
		}).delegate(".datepicker-right","click",function(){//向后切一个固定时次
			if(!$drop.find(".datepicker-realTimePush-btn").hasClass("active")){
				cfg.curDate = getDate(new Date(cfg.curDate),cfg.timeInterval,cfg);
				$date.find("span").text(getShowDate(cfg));
				if(5 == cfg.type){
					$date.next(".datepicker-hour").find("span:first").text(new Date(cfg.curDate).format("hh"));
				}else if(-1 != $.inArray(cfg.type,[8,10])){
					$date.siblings(".datepicker-hoursel").find("span:first").text(new Date(cfg.curDate).format("hh"));
					if("M" == cfg.dateType){
						$date.siblings(".datepicker-minsel").find("span:first").text(new Date(cfg.curDate).format("mm"));
					}
				}
				if($date.find(".date-pick-wrap").is(":visible")){
					buildDateLayer($date,cfg);
				}
				if($.isFunction(cfg.call)){
					cfg.call(cfg.curDate);
				}
			}
		}).delegate(".datepicker-rright","click",function(){//向后切一个范围时次
			cfg.curDate = getDate(new Date(cfg.curDate),parseInt($(this).text()) * ("M" == cfg.dateType ? 60 : 1),cfg);
			$date.find("span").text(getShowDate(cfg));
			$date.siblings(".datepicker-hoursel").find("span:first").text(new Date(cfg.curDate).format("hh"));
			if("M" == cfg.dateType){
				$date.siblings(".datepicker-minsel").find("span:first").text(new Date(cfg.curDate).format("mm"));
			}
			if($date.find(".date-pick-wrap").is(":visible")){
				buildDateLayer($date,cfg);
			}
			if($.isFunction(cfg.call)){
				cfg.call(cfg.curDate);
			}
		}).delegate(".datepicker-query","click",function(){//触发查询回调事件
			if(!$drop.find(".datepicker-realTimePush-btn").hasClass("active")){
				$date.find(".date-pick-wrap").remove();
				cfg.curDate = getDate(new Date(cfg.curDate),0,cfg);
				$date.find("span").text(getShowDate(cfg));
				if($.isFunction(cfg.call)){
					cfg.call(cfg.curDate);
				}
			}
		}).delegate(".datepicker-refresh","click",function(){//获取最新时间
			if(!$drop.find(".datepicker-realTimePush-btn").hasClass("active")){
				cfg.curDate = getDate(new Date(),0,cfg);
				$date.find("span").text(getShowDate(cfg));
				if(5 == cfg.type){
					$date.next(".datepicker-hour").find("span:first").text(new Date(cfg.curDate).format("hh"));
				}else if(-1 != $.inArray(cfg.type,[8,10])){
					$date.siblings(".datepicker-hoursel").find("span:first").text(new Date(cfg.curDate).format("hh"));
					if("M" == cfg.dateType){
						$date.siblings(".datepicker-minsel").find("span:first").text(new Date(cfg.curDate).format("mm"));
					}
				}
				if($date.find(".date-pick-wrap").is(":visible")){
					buildDateLayer($date,cfg);
				}
				if($.isFunction(cfg.call)){
					cfg.call(cfg.curDate);
				}
			}
		}).delegate(".datepicker-timeInterval","click",function(){//时间间隔切换
			if(!$drop.find(".datepicker-realTimePush-btn").hasClass("active")){
				if($drop.find(".date-pick-wrap").is(":visible")){
					$drop.find(".date-pick-wrap").remove();
				}
				var $timeInterval = $(this).find(".dp-timeInterval-wrap");
				if($timeInterval.length > 0){
                    $timeInterval.remove();
				}else{
                    buildTimeIntervalLayer($(this),cfg);
				}
			}
		}).delegate(".datepicker-realTimePush-btn","click",function(){//实时推送开关
			var dateSelStr = ".datepicker-date,.datepicker-left,.datepicker-right,.datepicker-query,.datepicker-refresh,.datepicker-timeInterval";
			if($(this).hasClass("off")){
				cfg.curDate = getDate(new Date(),0,cfg);
				$date.find("span").text(getShowDate(cfg));
				
				$drop.find(dateSelStr).css("cursor","pointer");
				$(this).removeClass("off");
				if($.isFunction(cfg.off)){
					cfg.off();
				}
			}else{
				$drop.find(dateSelStr).css("cursor","default");
				$drop.find(".date-pick-wrap").hide();
				$(this).addClass("off");
				if($.isFunction(cfg.on)){
					cfg.on();
				}
			}
		}).delegate(".datepicker-hour>span:first","click",function(){//选择小时
			if(!$(this).hasClass("active")){
				if($date.find(".date-pick-wrap").is(":visible")){
					$date.find(".date-pick-wrap").remove();
				}
				$(this).addClass("active");
				var $hourSel = $('<div>');
				$hourSel.addClass("datepicker-hour-select-wrap");
				$.each(cfg.customHm,function(i,h){
					var $h = $('<span>');
					if(h < 10){
						$h.text("0"+h);
					}else{
						$h.text(h);
					}
					$hourSel.append($h);
				});
				$hourSel.css("width",Math.ceil(cfg.customHm.length/4)*27+"px");
				$(this).after($hourSel);
				
				$hourSel.off().on("click","span",function(){
					$(this).parent().prev().removeClass("active").text($(this).text());
					$(this).parent().remove();
					if($.isFunction(cfg.call)){
						cfg.call(cfg.curDate);
					}
				});
			}
		});
		$(document).on('mousedown',function(ev){
			if(0 == $(ev.target).closest(cfg.appendTo).length){
				var $pick = $drop.find(".date-pick-wrap");
                if(!cfg.isClkBtnQuery &&  $pick.is(":visible") && $.isFunction(cfg.call)){
                    cfg.call(cfg.curDate);
                }
                if($pick.is(":visible") && $.isFunction(cfg.updateDateCall)){
                    cfg.updateDateCall();
                }
				$drop.find(".date-pick-wrap").remove();
				$drop.find(".datepicker-hour span").removeClass("active");
				$drop.find(".datepicker-hour-select-wrap").remove();
				$drop.find(".dp-timeInterval-wrap").remove();
				$drop.find(".datepicker-hmsel").remove();
			}
		});
		bindDateEvent($date,cfg);
	}
	/**
	 * 获取日期
	 */
	function getDate(date,step,cfg){
		var getVal = function(val){
			return Math.floor(val/cfg.timeInterval)*cfg.timeInterval;
		};
		if(!cfg.dateFmt.endsWith("dd")){
			if(cfg.dateFmt.endsWith("hh")){
				var hour = date.getHours();
				if(cfg.customHm.length > 0){
					if(hour < cfg.customHm[0]){
						date.setDate(date.getDate()-1);
						hour = cfg.customHm[cfg.customHm.length-1];
					}else{
						for(var i = cfg.customHm.length-1; i>=0 ; i--){
							if(hour >= cfg.customHm[i]){
								hour = cfg.customHm[i];
								break;
							}
						}
					}
				}else{
					hour = getVal(hour);
				}
				date.setHours(hour+step);
			}else{
				var min = date.getMinutes();
				if(cfg.customHm.length > 0){
					cfg.customHm = cfg.customHm.sort();
					if(min < cfg.customHm[0]){
						date.setHours(date.getHours()-1);
						min = cfg.customHm[cfg.customHm.length-1];
					}else{
						for(var i = cfg.customHm.length-1; i>=0 ; i--){
							if(min >= cfg.customHm[i]){
								min = cfg.customHm[i];
								break;
							}
						}
					}
				}else{
					if(cfg.dateFmt.endsWith("yyyy")){
                        date.setFullYear(date.getFullYear() + step,0,1);
                        date.setHours(0,0);
					}else if(cfg.dateFmt.endsWith("MM")){
                        date.setMonth(date.getMonth() + step,1);
                        date.setHours(0,0);
					}else{
                        date.setMinutes(getVal(min)+step);
					}
				}
			}
		}else{
			if(5 == cfg.type){
				var hour = date.getHours();
				if(cfg.customHm.length > 0){
					if(hour < cfg.customHm[0]){
						date.setDate(date.getDate()-1);
						hour = cfg.customHm[cfg.customHm.length-1];
					}else{
						for(var i = cfg.customHm.length-1; i>=0 ; i--){
							if(hour >= cfg.customHm[i]){
								hour = cfg.customHm[i];
								break;
							}
						}
					}
				}
				date.setHours(hour+step);
			}else if(-1 != $.inArray(cfg.type,[8,10])){
				if("M" == cfg.dateType){
					date.setMinutes(getVal(date.getMinutes())+step);
				}else{
                    var hour = date.getHours();
                    var hmArr = cfg.customHm;
					if(cfg.timeInterval < 24){
                        hmArr = $.grep(cfg.customHm,function(n){return cfg.customHm[0] == n % cfg.timeInterval});
					}
                    if(hmArr.length > 0){
                        if(hour < hmArr[0]){
                            date.setDate(date.getDate()-1);
                            hour = hmArr[hmArr.length-1];
                        }else{
                            for(var i = hmArr.length-1; i>=0 ; i--){
                                if(hour >= hmArr[i]){
                                    hour = hmArr[i];
                                    break;
                                }
                            }
                        }
                    }else{
                        hour = getVal(date.getHours());
					}
					date.setHours(hour+step);
				}
			}else{
				date.setDate(date.getDate()+step);
			}
		}
		return date.toString("yyyy-MM-dd hh:mm");
	}
	/**
	 * 创建日期选择界面
	 */
	function buildDateLayer($date,cfg){
		$date.find(".date-pick-wrap").remove();
		var $wrap = $("<div>").addClass("date-pick-wrap");
		var $p = $date.parent().parent();
		if($("body").width() - $p.offset().left < 298){
			$wrap.css("left","-60px");
		}
		$date.append($wrap);
		var $operateLayer = $("<div>").addClass("dp-month-year-opera");
		$wrap.append($operateLayer);
		if(cfg.dateFmt.endsWith("yyyy") || cfg.dateFmt.endsWith("MM")){
            buildTimeOperateLayerForYM($operateLayer,cfg);
		}else{
            buildTimeOperateLayer($operateLayer,cfg);
		}

		var $dpDateMain = $("<div>").addClass("dp-date-main");
		$wrap.append($dpDateMain);
		
		var $dpDateWrap = $("<div>").addClass("dp-date-wrap");
		$dpDateMain.append($dpDateWrap);
        if(cfg.dateFmt.endsWith("yyyy")){
            buildDateContentForY($dpDateWrap,cfg);
        }else if(cfg.dateFmt.endsWith("MM")){
            buildDateContentForM($dpDateWrap,cfg);
		}else{
            buildDateContent($dpDateWrap,cfg);
		}
		if(-1 != cfg.dateFmt.indexOf("hh")){
			var $dpHmWrap = $("<div>").addClass("dp-hm-wrap");
			$dpDateMain.append($dpHmWrap);
			buildHmLayer($dpHmWrap,cfg);
		}else{
			$wrap.css("height","238px");
			$dpDateMain.css("height","210px");
		}
	}
	/**
	 * 创建日期选择-操作区界面
	 */
	function buildTimeOperateLayer($operateLayer,cfg){
		var showDate = new Date(cfg.curDate);
		var yearStr = showDate.format("yyyy");
		var monthStr = showDate.format("MM");
		$operateLayer.append($('<div>').addClass("dp-year-prev"));
		$operateLayer.append($('<div>').addClass("dp-month-prev"));
		var $dateDiv = $('<div>').addClass("dp-month-year-content");
		$dateDiv.append($('<div>').addClass("dp-month-year-content-year").text(yearStr))
				.append($('<div>').addClass("dp-month-year-content-with").text("年"))
				.append($('<div>').addClass("dp-month-year-content-month").text(monthStr))
				.append($('<div>').addClass("dp-month-year-content-with").text("月"));
		$operateLayer.append($dateDiv);
		$operateLayer.append($('<div>').addClass("dp-month-next"));
		$operateLayer.append($('<div>').addClass("dp-year-next"));
		
		var $ys = $('<div>').addClass("dp-year-select");
		$ys.append($('<div>').addClass("year-area"));
		var $yac = $('<div>').addClass("year-area-control");
		var $yacl = $('<div>').addClass("year-area-controlleft");
		$yacl.append($('<i>').addClass("dp-btn-icon cafe-ifont cafe-ic-xiangyou2"));
		var $yacr = $('<div>').addClass("year-area-controlright");
		$yacr.append($('<i>').addClass("dp-btn-icon cafe-ifont cafe-ic-xiangyou2"));
		$yac.append($yacl).append($yacr);
		$ys.append($yac);
		var $ms = $('<div>').addClass("dp-month-select");
		$.each([1,7,2,8,3,9,4,10,5,11,6,12],function(i,m){
			$ms.append($('<div>').text(m));
		});
		$operateLayer.append($ys).append($ms);
	}
    /**
     * 创建日期选择-操作区界面
     */
    function buildTimeOperateLayerForYM($operateLayer,cfg){
        $operateLayer.append($('<div>').addClass("dp-year-prev"));
        var $dateDiv = $('<div>').addClass("dp-month-year-content").css({
            cursor : "default",
            width : "77px",
            margin : "0 64px"
		});
        var showDate = new Date(cfg.curDate);
        var yearStr = showDate.format("yyyy");
        if(cfg.dateFmt.endsWith("yyyy")){
            $dateDiv.css({
                cursor : "default",
                width : "95px",
                margin : "0 55px"
			});
            var startyear = showDate.getFullYear() - 9;
            var endyear = showDate.getFullYear() + 2;
            yearStr =startyear + "-" + endyear;
        }
        $dateDiv.append($('<div>').addClass("dp-month-year-content-year").text(yearStr))
            .append($('<div>').addClass("dp-month-year-content-with").text("年"));
        $operateLayer.append($dateDiv);
        $operateLayer.append($('<div>').addClass("dp-year-next"));
    }
	/**
	 * 创建日期选择-日期显示界面
	 */
	function buildDateContent($dpDateWrap,cfg){
		var showDate = new Date(cfg.curDate);
		var curYear = showDate.getFullYear();
		var curMonth = showDate.getMonth();
		var curDate = showDate.getDate();
		var maxDate = getMonthMaxDate(cfg);
		
		$dpDateWrap.empty();
		var $dateTable = $("<table>").addClass("dp-date-table");
		$dpDateWrap.append($dateTable);
		var tableHeader = $("<tr>").addClass("dp-date-table-header");
		$dateTable.append(tableHeader);
		$.each(["周日", "周一", "周二", "周三", "周四", "周五", "周六"],function(i, weekStr){
			tableHeader.append($("<th>").addClass("dp-header-cell").text(weekStr));
		});
		
		var tdArr = [];
		var dateLeftPad = new Date(curYear, curMonth, 1).getDay();
		for(var i = dateLeftPad; i > 0; i--){
			var _dateT = new Date(new Date(curYear, curMonth, 1).getTime());
			_dateT.setDate(_dateT.getDate()-i);
			var dateStr = parseInt(_dateT.format("dd"));
			tdArr.push("<td class='dp-date-cell dp-other-month-date'>" + dateStr + "</td>");
		}
		if(curDate > maxDate){
			curDate = maxDate;
		}
		for(var i = 1; i <= maxDate; i++){
			var clazz = "dp-date-cell dp-date-cell-valid";
			if(i == curDate){
				clazz += " dp-date-select";
			}
			tdArr.push("<td class='" + clazz + "'>" + i + "</td>");
		}
		
		var dateRightPad = 6 - new Date(curYear, curMonth, maxDate).getDay();
		for(var i = 1; i <= dateRightPad; i++){
			var _dateT = new Date(new Date(curYear, curMonth, maxDate).getTime());
			_dateT.setDate(_dateT.getDate()+i);
			var dateStr = parseInt(_dateT.format("dd"));
			tdArr.push("<td class='dp-date-cell dp-other-month-date'>" + dateStr + "</td>")
		}
		var maxPad = dateRightPad + (42 - tdArr.length);
		for(var i = dateRightPad + 1; i <= maxPad; i++){
			var _dateT = new Date(new Date(curYear, curMonth, maxDate).getTime());
			_dateT.setDate(_dateT.getDate()+i);
			var dateStr = parseInt(_dateT.format("dd"));
			tdArr.push("<td class='dp-date-cell dp-other-month-date'>" + dateStr + "</td>")
		}
		
		for(var i = 0; i < tdArr.length; i += 7){
			$dateTable.append("<tr>" + tdArr.slice(i, i + 7).join("") + "</tr>");
		}
	}
    /**
     * 创建日期选择-日期显示界面
     */
    function buildDateContentForY($dpDateWrap,cfg){
        var showDate = new Date(cfg.curDate);
        var curYear = showDate.getFullYear();
        var startyear = curYear - 9;
        $dpDateWrap.empty();
        var $dateTable = $("<table>").addClass("dp-date-table");
        $dpDateWrap.append($dateTable);

        var $tr = $("<tr>");
        for(var i = 0; i < 12; i++){
            if(0 == i % 4){
                $tr = $("<tr>");
                $dateTable.append($tr);
            }
            $tr.append($("<td>").css("font-size","14px").addClass("dp-date-cell dp-date-cell-valid").attr("year",startyear).append($("<span>").text(startyear)));
            startyear++;
        }
        $dateTable.find("td[year='"+curYear+"']").addClass("dp-ym-select");
    }
    /**
     * 创建日期选择-日期显示界面
     */
    function buildDateContentForM($dpDateWrap,cfg){
        var showDate = new Date(cfg.curDate);
        var curMonth = showDate.getMonth() + 1;
        $dpDateWrap.empty();
        var $dateTable = $("<table>").addClass("dp-date-table");
        $dpDateWrap.append($dateTable);

        var $tr = $("<tr>");
        $.each([{id : 1, name : "一月"},{id : 2, name : "二月"},{id : 3, name : "三月"},
            {id : 4, name : "四月"},{id : 5, name : "五月"},{id : 6, name : "六月"},
            {id : 7, name : "七月"},{id : 8, name : "八月"},{id : 9, name : "九月"},
            {id : 10, name : "十月"},{id : 11, name : "十一月"},{id : 12, name : "十二月"}],function(i){
            if(0 == i % 4){
                $tr = $("<tr>");
                $dateTable.append($tr);
            }
            $tr.append($("<td>").css("font-size","14px").addClass("dp-date-cell dp-date-cell-valid").attr("month",this.id).append($("<span>").text(this.name)));
        });
        $dateTable.find("td[month='"+curMonth+"']").addClass("dp-ym-select");
    }
	/**
	 * 创建日期选择-小时分钟选择界面
	 */
	function buildHmLayer($dpHmWrap,cfg){
		var showDate = new Date(cfg.curDate);
		var $hourLayerWrap = $("<div class='dp-hm-select-wrap'>");
		$dpHmWrap.append($hourLayerWrap);
		var $hourLayer = $("<div id='DateHour' class='dp-hm-select'>");
		$hourLayerWrap.append($hourLayer);
		$hourLayerWrap.append("小时");
		var curHour = showDate.format("hh");
		$hourLayer.append($('<div class="dp-hm-content">').text(curHour));
		$hourLayer.append('<div class="dp-hm-icon">');
		if(cfg.dateFmt.endsWith("mm")){
			var $minuteLayerWrap = $("<div class='dp-hm-select-wrap'>");
			$dpHmWrap.append($minuteLayerWrap);
			var $minuteLayer = $("<div id='DateMinute' class='dp-hm-select'>");
			$minuteLayerWrap.append($minuteLayer);
			$minuteLayerWrap.append("分钟");
			var curMinute = showDate.format("mm");
			$minuteLayer.append($('<div class="dp-hm-content">').text(curMinute));
			$minuteLayer.append('<div class="dp-hm-icon">');
		}
	}
	
	/**
	 * 绑定日期选择界面上的事件
	 */
	function bindDateEvent($wrap,cfg){
		$wrap.undelegate().delegate(".dp-month-year-content-year","click",function(event){//显示年份选择界面
			event.stopPropagation();
			if(-1 != cfg.dateFmt.indexOf("dd")){
                if($(this).hasClass("dp-select")){
                    $wrap.find(".dp-year-select").hide();
                    $(this).removeClass("dp-select");
                }else{
                    var yearStr = new Date(cfg.curDate).format("yyyy");
                    var $ya = $wrap.find(".dp-year-select .year-area").empty();
                    $.each([0,5,1,6,2,7,3,8,4,9],function(i,m){
                        $ya.append($('<div>').text(Number(yearStr)+m));
                    });
                    $wrap.find(".dp-year-select").show();
                    $(this).siblings(".dp-month-year-content-month").removeClass("dp-select");
                    $wrap.find(".dp-month-select").hide();
                    $(this).addClass("dp-select");
                }
			}
		}).delegate(".dp-month-year-content-month","click",function(event){//显示月份选择界面
			event.stopPropagation();
			if($(this).hasClass("dp-select")){
				$wrap.find(".dp-month-select").hide();
				$(this).removeClass("dp-select");
			}else{
				$wrap.find(".dp-month-select").show();
				$(this).siblings(".dp-month-year-content-year").removeClass("dp-select");
				$wrap.find(".dp-year-select").hide();
				$(this).addClass("dp-select");
			}
		}).delegate(".dp-year-prev","click",function(event){//上一个年份
			event.stopPropagation();
			var curDate = new Date(cfg.curDate);
			curDate.setFullYear(curDate.getFullYear()-1);
			cfg.curDate = getDate(curDate,0,cfg);
			$wrap.find(".dp-month-year-content-year").text(curDate.format("yyyy"));
			$wrap.find("span").text(getShowDate(cfg));
			buildDateLayer($wrap,cfg);
		}).delegate(".dp-year-next","click",function(event){//下一个年份
			event.stopPropagation();
			var curDate = new Date(cfg.curDate);
			curDate.setFullYear(curDate.getFullYear()+1);
			cfg.curDate = getDate(curDate,0,cfg);
			$wrap.find(".dp-month-year-content-year").text(curDate.format("yyyy"));
			$wrap.find("span").text(getShowDate(cfg));
			buildDateLayer($wrap,cfg);
		}).delegate(".dp-month-prev","click",function(event){//上一个月份
			event.stopPropagation();
			var curDate = new Date(cfg.curDate);
			curDate.setMonth(curDate.getMonth()-1);
			cfg.curDate = getDate(curDate,0,cfg);
			$wrap.find(".dp-month-year-content-month").text(curDate.format("MM"));
			$wrap.find("span").text(getShowDate(cfg));
			buildDateLayer($wrap,cfg);
		}).delegate(".dp-month-next","click",function(event){//下一个月份
			event.stopPropagation();
			var curDate = new Date(cfg.curDate);
			curDate.setMonth(curDate.getMonth()+1);
			cfg.curDate = getDate(curDate,0,cfg);
			$wrap.find(".dp-month-year-content-month").text(curDate.format("MM"));
			$wrap.find("span").text(getShowDate(cfg));
			buildDateLayer($wrap,cfg);
		}).delegate(".dp-date-cell-valid","click",function(event){//切换日期
			event.stopPropagation();
            var isQuery = !$wrap.siblings(".datepicker-dateCtl").find(".datepicker-query").is(":visible");
			if(!$(this).hasClass("dp-date-select")){
                $wrap.find(".dp-date-table td.dp-date-cell-valid").removeClass("dp-date-select dp-ym-select");
				var curDate = new Date(cfg.curDate);
				if(cfg.dateFmt.endsWith("yyyy")){
                    $(this).addClass("dp-ym-select");
                    curDate.setFullYear($(this).attr("year"));
				}else if(cfg.dateFmt.endsWith("MM")){
                    $(this).addClass("dp-ym-select");
                    curDate.setMonth($(this).attr("month") - 1);
				}else{
                    $(this).addClass("dp-date-select");
                    curDate.setDate($(this).text());
				}
				cfg.curDate = getDate(curDate,0,cfg);
				$wrap.find("span").text(getShowDate(cfg));

			}
            if(isQuery){
                $wrap.find(".date-pick-wrap").remove();
            }
            if(isQuery && $.isFunction(cfg.call)){
                cfg.call(cfg.curDate);
            }
		}).delegate("#DateHour","click",function(event){//选择小时
			event.stopPropagation();
			$(this).css({"background-color":"rgba(19, 99, 189, 0.8)", 'border': '1px solid #1364bb'});
			$(this).find(".dp-hm-icon").css({
				"top" : "3px",
				"border-top" : "5px solid transparent",
				"border-bottom" : "5px solid #ffffff"
			});
			buildHourOptions($wrap,$(this).parents(".dp-hm-select-wrap"),cfg);
		}).delegate("#DateMinute","click",function(event){//选择分钟
			event.stopPropagation();
			$(this).css({"background-color":"rgba(19, 99, 189, 0.8)","border":"1px solid rgb(19, 100, 187)"});
			$(this).find(".dp-hm-icon").css({
				"top" : "3px",
				"border-top" : "5px solid transparent",
				"border-bottom" : "5px solid #ffffff"
			});
			buildMinuteOptions($wrap,$(this).parents(".dp-hm-select-wrap"),cfg);
		}).delegate(".year-area>div","click",function(event){//选择年份
			event.stopPropagation();
			var showDate = new Date(cfg.curDate);
			showDate.setFullYear(parseInt($(this).text(), 10));
			cfg.curDate = getDate(showDate,0,cfg);
			$wrap.find("span").text(getShowDate(cfg));
			$wrap.find(".dp-year-select").hide();
			buildDateLayer($wrap,cfg);
		}).delegate(".year-area-controlleft","click",function(event){//向左切换年份
			event.stopPropagation();
			var yearStr = $wrap.find(".dp-year-select .year-area>div:eq(0)").text();
			var year = parseInt(yearStr, 10) - 10;
			var $ya = $wrap.find(".dp-year-select .year-area").empty();
			$.each([0,5,1,6,2,7,3,8,4,9],function(i,m){
				$ya.append($('<div>').text(year+m));
			});
		}).delegate(".year-area-controlright","click",function(event){//向右切换年份
			event.stopPropagation();
			var yearStr = $wrap.find(".dp-year-select .year-area>div:eq(0)").text();
			var year = parseInt(yearStr, 10) + 10;
			var $ya = $wrap.find(".dp-year-select .year-area").empty();
			$.each([0,5,1,6,2,7,3,8,4,9],function(i,m){
				$ya.append($('<div>').text(year+m));
			});
		}).delegate(".dp-month-select>div","click",function(event){//选择月份
			event.stopPropagation();
			var showDate = new Date(cfg.curDate);
			showDate.setMonth(parseInt($(this).text(), 10)-1);
			cfg.curDate = getDate(showDate,0,cfg);
			$wrap.find("span").text(getShowDate(cfg));
			$wrap.find(".dp-month-select").hide();
			buildDateLayer($wrap,cfg);
		});
	}
	/**
	 * 小时选择框
	 */
	function buildHourOptions($wrap,$hourLayerWrap,cfg){
		$wrap.find('.dp-hm-options').remove();
		if(-1 == $.inArray(cfg.type,[8,10])){
			$wrap.find("#DateMinute").removeAttr("style").find(".dp-hm-icon").removeAttr("style");
		}else{
			$wrap.find(".date-pick-wrap").remove();
		}
		var $hourOptions = $('<div class="dp-hm-options">');
		$hourLayerWrap.append($hourOptions);
		var hourData = [];
		if("H" == cfg.dateType && cfg.customHm.length > 0){
            hourData = cfg.customHm;
			if(cfg.timeInterval < 24){
                hourData = $.grep(cfg.customHm,function(n){return cfg.customHm[0] == n % cfg.timeInterval});
			}
		}else{
            for(var i = 0; i < 24; i++){
                var _curDate = new Date(cfg.curDate);
                _curDate.setHours(i);
                var hour = parseInt(new Date(getDate(_curDate,0,cfg)).format("hh"));
                if(-1 == $.inArray(hour,hourData)){
                    hourData.push(hour);
                }
            }
		}
		hourData.sort(function(a,b){
			return a-b;
		});
		$hourOptions.height(27 + (32 * Math.ceil(hourData.length / 6)));
		$hourOptions.append("<div class='dp-hm-option-title'>小时选择</div>");
		var showDate = new Date(cfg.curDate);
		var curHour = showDate.format("hh");
		$.each(hourData,function(i,hour){
			hour = prefixInteger(hour);
			var $hourOption =$("<div class='dp-hm-option'>").text(hour);
			if(hour == curHour){
				$hourOption = $("<div class='dp-hm-option dp-hm-option-selected'>").text(hour);
			}
			$hourOptions.append($hourOption);
		});
		$hourOptions.find(".dp-hm-option").unbind().bind("click", function(e){
			e.stopPropagation();
			if(!$(this).hasClass("dp-hm-option-selected")){
				$(this).addClass("dp-hm-option-selected").siblings(".dp-hm-option").removeClass("dp-hm-option-selected");
				showDate.setHours(parseInt($(this).text(), 10));
				cfg.curDate = showDate.format("yyyy-MM-dd hh:mm");
				if(-1 == $.inArray(cfg.type,[8,10])){
					$wrap.find("span").text(getShowDate(cfg));
					$(this).parent().hide().parent().find(".dp-hm-icon").removeAttr("style");
					$(this).parent().hide().parent().removeAttr("style").find(".dp-hm-content").text($(this).text());
				}else{
					$wrap.find(".datepicker-hoursel").find("span:first").text($(this).text());
					$(this).closest(".datepicker-hmsel").remove();
				}
			}
		});
		$hourOptions.show();
	}
	/**
	 * 分钟选择框
	 */
	function buildMinuteOptions($wrap,$minuteLayerWrap,cfg){
		$wrap.find('.dp-hm-options').remove();
		if(-1 == $.inArray(cfg.type,[8,10])){
			$wrap.find("#DateHour").removeAttr("style").find(".dp-hm-icon").removeAttr("style");
		}else{
			$wrap.find(".date-pick-wrap").remove();
		}
		var $minuteOptions = $('<div class="dp-hm-options">');
		$minuteLayerWrap.append($minuteOptions);
		var minuteData = [];
		for(var i = 0; i < 60; i++){
			var _curDate = new Date(cfg.curDate);
			_curDate.setMinutes(i);
			var min = parseInt(new Date(getDate(_curDate,0,cfg)).format("mm"));
			if(-1 == $.inArray(min,minuteData)){
				minuteData.push(min);
			}
		}
		minuteData.sort(function(a,b){
			return a-b;
		});
		$minuteOptions.height(27 + (32 * Math.ceil(minuteData.length / 6)));
		$minuteOptions.append("<div class='dp-hm-option-title'>分钟选择</div>");
		var showDate = new Date(cfg.curDate);
		var curMin = new Date(cfg.curDate).format("mm");
		$(minuteData).each(function(i, minute){
			minute = prefixInteger(minute);
			var $minuteOption = $("<div class='dp-hm-option'>").text(minute);
			if(minute == curMin){
				$minuteOption = $("<div class='dp-hm-option dp-hm-option-selected'>").text(minute);
			}
			$minuteOptions.append($minuteOption);
		});
		$minuteOptions.find(".dp-hm-option").unbind().bind("click", function(e){
			e.stopPropagation();
			if(!$(this).hasClass("dp-hm-option-selected")){
				$(this).addClass("dp-hm-option-selected").siblings(".dp-hm-option").removeClass("dp-hm-option-selected");
				showDate.setMinutes(parseInt($(this).text(), 10));
				cfg.curDate = showDate.format("yyyy-MM-dd hh:mm");
				if(-1 == $.inArray(cfg.type,[8,10])){
					$wrap.find("span").text(getShowDate(cfg));
					$(this).parent().hide().parent().find(".dp-hm-icon").removeAttr("style");
					$(this).parent().hide().parent().removeAttr("style").find(".dp-hm-content").text($(this).text());
				}else{
					$wrap.find(".datepicker-minsel").find("span:first").text($(this).text());
					$(this).closest(".datepicker-hmsel").remove();
				}
			}
		});
		$minuteOptions.show();
	}
	/**
	 * 时间间隔选择框
	 */
	function buildTimeIntervalLayer($timeInterval,cfg){
		$timeInterval.find(".dp-timeInterval-wrap").remove();
		var $curTimeInterval = $timeInterval.find("span:first");
		var $ul = $('<ul>');
		$ul.addClass("dp-timeInterval-wrap");
		if(cfg.timeIntervals){
			$.each(cfg.timeIntervals,function(i,ti){
				var $li = $('<li>');
				$li.attr({"lid" : ti.id, "ltype" : ti.type}).text(ti.text);
				$ul.append($li);
			});
			//选择时间间隔
			$timeInterval.append($ul).off().on("click",".dp-timeInterval-wrap>li",function(){
				$curTimeInterval.text($(this).text());
				$(this).closest(".dp-timeInterval-wrap").remove();
				cfg.timeInterval = parseInt($(this).attr("lid"));
				cfg.dateType = $(this).attr("ltype");
				var $dp = $timeInterval.closest(".datepicker");
                $dp.find(".datepicker-left>span,.datepicker-right>span").text($(this).attr("lid"));
				if(10 == cfg.type){
                    if("H" == cfg.dateType){
                    	if(cfg.timeInterval >= 24 && !cfg.customHm){
                            $dp.find(".datepicker-hoursel").hide();
						}else{
                            $dp.find(".datepicker-hoursel").show();
						}
                        $dp.find(".datepicker-minsel").hide();
                    }else{
                        $dp.find(".datepicker-minsel").show();
					}
                    cfg.curDate = getDate(new Date(cfg.curDate),0,cfg);
                    var showDate = new Date(cfg.curDate);
					$dp.find(".datepicker-date>span").text(showDate.format("yyyy-MM-dd"));
					$dp.find(".datepicker-hoursel>span:first").text(showDate.format("hh"));
					$dp.find(".datepicker-minsel>span:first").text(showDate.format("mm"));
				}else{
                    if("H" == cfg.dateType){
                        cfg.dateFmt = "yyyy-MM-dd hh";
                    }else{
                        cfg.dateFmt = "yyyy-MM-dd hh:mm";
                    }
				}
			});
		}
	}
	/**
	 * 自动补0
	 * @param num 需要前面补0的数值
	 * @param n 需要的长度
	 */
	function prefixInteger(num,n){
		if(!n){
			n = 2;
		}
		return (Array(n).join(0)+num).slice(-n);
	}
	/**
	 * 获取月份最大日期
	 */
	function getMonthMaxDate(cfg){
		return dateUtil.getMaxDateForMonth(new Date(cfg.curDate));
	}
	function getShowDate(cfg){
		return new Date(cfg.curDate).format(cfg.dateFmt);
	}
	var CFDatepicker = function(settings){
		var options = {
				appendTo: '',//控件所在容器
				dateFmt : 'yyyy-MM-dd hh:mm',//日期格式
				timeInterval : 5,//时间间隔，默认5分钟
				ttimeInterval : 1,//时间间隔，默认1小时
				dateType : "M",//日期显示类型['H'|'M'],仅当type为8时有效,默认M
				type : 0,//日期控件类型[0|1|2|3]
				customHm : [],//自定义小时和分钟
				timeIntervals : null,//时间间隔数组
				curDate: null,//控件上的时间
				loadSucc : null,//控件初始化结束,
				isClkBtnQuery : true,//是否点击按钮查询
				call : null,//控件点击事件
				updateDateCall: null,//日期变更回调方法
                webSocketOpt : null//webSocket配置信息
		};
		this.config = $.extend({},options, settings);
		if(!this.config.curDate){
			this.config.curDate = getDate(new Date(),0,this.config);
		}else{
			if(-1 == $.inArray(this.config.type,[8,10])){
				if(this.config.customHm.length > 0){
					if(this.config.dateFmt.endsWith("hh")){
						this.config.curDate = this.config.curDate.substr(0,16);
					}else if(this.config.dateFmt.endsWith("dd")){
						this.config.curDate = this.config.curDate.substr(0,13) + ":00";
					}else if(this.config.dateFmt.endsWith("MM")){
                        this.config.curDate = this.config.curDate.substr(0,7) + "-01 00:00";
                    }else if(this.config.dateFmt.endsWith("yyyy")){
                        this.config.curDate = this.config.curDate.substr(0,4) + "-01-01 00:00";
                    }
				}else{
					if(this.config.dateFmt.endsWith("hh")){
						this.config.curDate = this.config.curDate.substr(0,13) + ":00";
					}else if(this.config.dateFmt.endsWith("dd")){
						this.config.curDate = this.config.curDate.substr(0,10) + " 00:00";
					}else if(this.config.dateFmt.endsWith("MM")){
                        this.config.curDate = this.config.curDate.substr(0,7) + "-01 00:00";
                    }else if(this.config.dateFmt.endsWith("yyyy")){
                        this.config.curDate = this.config.curDate.substr(0,4) + "-01-01 00:00";
                    }
				}
			}
			this.config.curDate = getDate(new Date(this.config.curDate),0,this.config);
		}
		this.$drop = getNodeHtml(this.config);
		_eves(this.$drop,this.config);
		if(this.config.appendTo){
			$(this.config.appendTo).empty().append(this.$drop);
		}
		if($.isFunction(this.config.loadSucc)){
			this.config.loadSucc();
		}
	}
	
	CFDatepicker.prototype = {
		getVal : function(){//获取日期控件时间
			var curDate = getShowDate(this.config);
			if(5 == this.config.type){
				curDate += " "+this.$drop.find(".datepicker-hour>span:first").text()+":00";
			}else if(-1 != $.inArray(this.config.type,[8,10])){
				curDate += " "+this.$drop.find(".datepicker-hoursel>span:first").text();
				curDate += ":";
				if("M" == this.config.dateType){
					curDate += this.$drop.find(".datepicker-minsel>span:first").text();
				}else{
					curDate += "00";
				}
			}else{
                if(this.config.dateFmt.endsWith("hh")){
                    curDate = curDate.substr(0,13) + ":00";
                }else if(this.config.dateFmt.endsWith("dd")){
                    curDate = curDate.substr(0,10) + " 00:00";
                }
			}
            if(this.config.dateFmt.endsWith("MM")){
                curDate = curDate.substr(0,7) + "-01 00:00";
			}else if(this.config.dateFmt.endsWith("yyyy")){
                curDate = curDate.substr(0,4) + "-01-01 00:00";
			}
			return curDate;
		},
		setVal : function(val){//修改日期控件时间
			this.config.curDate = val;
			if(5 == this.config.type){
				this.config.curDate = this.config.curDate.substr(0,13) + ":00";
				this.$drop.find(".datepicker-hour>span:first").text(this.config.curDate.substr(11,2));
			}else{
                if(this.config.dateFmt.endsWith("hh")){
                    this.config.curDate = this.config.curDate.substr(0,13) + ":00";
                }else if(this.config.dateFmt.endsWith("dd")){
                    this.config.curDate = this.config.curDate.substr(0,10) + " 00:00";
                }
			}
            if(this.config.dateFmt.endsWith("MM")){
                this.config.curDate = this.config.curDate.substr(0,7) + "-01 00:00";
			}else if(this.config.dateFmt.endsWith("yyyy")){
                this.config.curDate = this.config.curDate.substr(0,4) + "-01-01 00:00";
            }
			this.$drop.find(".datepicker-date span").text(getShowDate(this.config));
		},
		setTimeIntervals : function(timeIntervals){//设置时效间隔选择列表
			this.config.timeIntervals = timeIntervals;
		},
		getTimeIntervals : function(){//获取时效间隔选择列表
			return this.config.timeIntervals;
		},
		getTimeInterval : function(){//获取当前时效间隔
			var timeInterval = this.config.timeInterval;
			if(-1 != $.inArray(this.config.type,[8,10])){
                timeInterval = "H" == this.config.dateType ? timeInterval * 60 : timeInterval;
			}else{
                if(this.config.dateFmt.endsWith("hh")){
                    timeInterval = this.config.timeInterval * 60;
                }else if(this.config.dateFmt.endsWith("dd")){
                    timeInterval = this.config.timeInterval * 24 * 60;
                }
			}
			return timeInterval;
		},
		isOpen : function(){//实时推送是否打开
			return this.$drop.find(".datepicker-realTimePush-btn").hasClass("active");
		},
		sendInfoToWebsocket : function(){//发送信息到websocket
			var websocket = this.$drop.find(".datepicker-realTimePush-btn").data("webSocket");
			if(websocket){
                var wso = this.config.webSocketOpt;
                websocket.bindUser(wso.service,wso.userId,wso.getWsTags());
			}
		},
		destroy: function() {
			$(this.config.appendTo).empty();
		}
	};
	
	CafeJS.Datepicker = function(settings){
		var drop =new CFDatepicker(settings);
		return drop;
	}
});